package com.ce.webframework.exception.support;

import java.text.MessageFormat;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ExceptionHandler;

import com.ce.webframework.i18n.ExceptionMessageLocale;



public final class StrutsExceptionHandler extends ExceptionHandler {
	private static final long serialVersionUID = 2631490367837964960L;
	private static final Logger logger = Logger.getLogger(StrutsExceptionHandler.class);
	public static final String WEBX_THE_EXCEPTION_KEY = "WEBX_THE_EXCEPTION_KEY";

	protected void storeException(HttpServletRequest request, String property, ActionMessage error,
			ActionForward forward, String scope) {
		Throwable cause = getExceptionFrmReqest(request);
		logger.warn("Exception Caught:", cause);
		/************* add 邓成东 进行异常信息国际化处理******begin*****/
		String message = cause.getMessage();
		String fileName = "";
		String key = "";
		String exceptionInfo = "";
		if(message != null && !"".equals(message)){
			/**示例:base:blog001,userName:blogName*/
			String[] allmessages = message.split(",");
			int arraynum = allmessages.length;
			String[] parm = null;
			if(arraynum > 1){//表示存在动态填充异常信息部分
				parm = allmessages[1].split(":");
			}
			String[] messages = allmessages[0].split(":");
			int length = messages.length;
			if(length == 1){//项目只有一个异常文件
				key = messages[0];
			}else if(length >= 2){//每个模块一个异常文件
				fileName = messages[0];
				key = messages[1];
			}
			ExceptionMessageLocale  ml = new ExceptionMessageLocale(request);
			String exceptionMessage = ml.getLocaleMessage(fileName,key);
			if(exceptionMessage == null){
				exceptionInfo = message;
			}else{
				MessageFormat form = new MessageFormat(exceptionMessage);
				if(parm != null && parm.length > 0){
					exceptionInfo =  form.format(parm);
				}else{
					exceptionInfo =  exceptionMessage;
				}

			}
		}
		System.out.println("exceptionInfo--->"+exceptionInfo);
		//错误页面用${exceptionMessage}读取异常信息
		request.setAttribute("exceptionMessage", exceptionInfo);
		/************* add 邓成东 进行异常信息国际化处理******end*****/

		ExceptionWrapper wrapper = ExceptionWrapperFactory.getExceptionWrapper(cause);
		if (wrapper != null) {
			error = ActionErrorUtil.getActionMessage(wrapper);
		} else {
			error = new ActionMessage(ActionErrorUtil.DEFAULT_ERR_CODE, cause.getMessage());
		}
		request.setAttribute(WEBX_THE_EXCEPTION_KEY, wrapper);
		property = error.getKey();
		super.storeException(request, property, error, forward, scope);
	}

	public Exception getExceptionFrmReqest(HttpServletRequest request) {
		return (Exception) request.getAttribute(Globals.EXCEPTION_KEY);
	}
}
